<template>
  <div class="main video_wrapper">
    <nav-bar class="home-nav">
      <div class="left" slot="left" @click="goBack">
        <van-icon name="arrow-left" size="24"/>
      </div>
      <div slot="center">视频数据</div>
      <div v-if="!showDelete" class="right" slot="right" @click="showDelete = true">编辑</div>
      <div v-else class="right" slot="right" @click="onSave">保存</div>
    </nav-bar>

    <div class="switch_name">
      <van-field
        readonly
        clickable
        name="picker"
        :value="value"
        label=""
        right-icon="arrow-down"
        placeholder=""
        @click="showPicker = true"
      />
    </div>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>

      <van-list
        v-model="loading"
        :finished="finished"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
         <div class="video_main">
          <div v-for="(item, index) in videoList" :key="index" @click="toDetail(item)" class="video_item">

            <van-image fit="cover" src="https://img.yzcdn.cn/vant/cat.jpeg" />
            <span class="delete"><van-icon name="bofang-" class="iconfont" class-prefix='icon' color="#fff" size="36"/></span>
            <span v-show="showDelete" @click.stop="onDelete(item)"><van-icon name="clear" color="#ff3b30" size="26"/></span>
            <div class="video_date">{{item.create_date}}</div>
          </div>
         </div>
      </van-list>



    <div class="add_btn"><label for="pop_video" id="labelr">
      <input style="display:none;" id="pop_video" type="file" accept="video/*" capture="camcorder"
             v-on:change="getVideo(event,'2')" name="fileTrans" ref="file" value="">
      <div class="inputVideo">选择上传视频</div>
    </label></div>


    <div class="upload_box">
      <van-popup v-model="show"
                 position="bottom"
                 :style="{ height: '100%' }"
                 :lazy-render="lazy_render"
                 closeable
      >
        <div>
          <h2 class="upload_box_title">上传视频</h2>
          <div class="video_preview">
            <video ref="videoId" id="videoId" controls width="100%" height="300"></video>
          </div>
          <div>
            <van-field
              readonly
              clickable
              name="datetimePicker"
              :value="valueTime"
              label="选择时间"
              placeholder="点击选择时间"
              @click="showTimePicker = true"
            />
            <van-popup v-model="showTimePicker" position="bottom">
              <van-datetime-picker
                v-model="currentDate"
                type="datetime"
                title="选择完整时间"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="onTimeConfirm"
                @cancel="showTimePicker = false"
              />
            </van-popup>
          </div>
        </div>
        <div class="add_btn">
          <van-button type="primary" color="#1692f2" @click="onUpVideo" block>确认上传</van-button>
        </div>

      </van-popup>
    </div>

  </div>
</template>

<script>
  import NavBar from "@/components/common/navbar/NavBar"

  export default {
    name: "videoList",
    components: {
      NavBar
    },

    data() {
      return {
        lazy_render: false,
        show: false, //展示上传图片层
        pid: '',
        bid: '',
        sid: '',
        videoFiles: '',
        list: [],
        loading: false,
        finished: false,

        page: 1,
        limit: 7,
        videoList: [],

        value: '',
        columns: [],
        showPicker: false,
        showDelete: false,
        valueTime: '',
        minDate: new Date(2020, 0, 1),
        maxDate: new Date(2025, 10, 1),
        currentDate: new Date(),
        showTimePicker: false,
        file: '',
      };
    },

    created() {
      this.pid = this.$route.query.pid;
      this.bid = this.$route.query.bid;
      this.getStageList();  // 调用阶段
    },

    mounted() {
    },

    methods: {
      //获取阶段
      getStageList() {
        let that = this;
        console.log('pid', that.pid)
        that.$http.get('/api/MobileAadminApi/getStageList', {pid: that.pid}, r => {
          console.log('阶段', r)
          that.value = r.data[0].name;
          that.sid = r.data[0].id;

          let Arr = [];
          r.data.map(item => {
            let Obj = {};
            Obj['sid'] = item.id;
            Obj['text'] = item.name
            Arr.push(Obj);
            return Arr;
          })
          this.columns = Arr
          console.log('阶段数组', Arr);

          that.getVideoList(); // 调用视频列表
        })
      },

      getVideoList() {
        let that = this;
        const params = {
          bid: that.bid,
          sid: that.sid,
          type: 1,
          page: that.page,
          limit: that.limit,
        };

        console.log('page',that.page)

        that.$http.get('/api/MobileAadminApi/getVideoList', params, r => {
          console.log('视频r:', r)
          if (r.code == 1) {
            let rows = r.data; //请求返回当页的列表
            console.log('rows', rows);
            that.loading = false;

            if (rows == null || rows.length === 0) {
              that.finished = true; // 加载结束
              return;
            }

            that.videoList = that.videoList.concat(...rows);
            that.page++;
            console.log('videoList', that.videoList)
            console.log('loading',that.loading)

          }
        })
      },

      onLoad() {
        this.getVideoList();
      },

      goBack() {
        this.$router.go(-1);
      },
      onConfirm(value) {
        this.videoList = [];
        this.page = 1;
        this.sid = value.sid;
        this.value = value.text;
        console.log('选择value', value)
        this.showPicker = false;
        this.getVideoList()
      },

      toDetail(event) {
        console.log('视频跳转详情event', event)
        this.$router.push({path: '/videoDetail', query: {sources: event.sources}})
      },

      onDelete(e) {
        console.log('删除e', e);
        let that = this;
        that.$http.get('/api/MobileAadminApi/deleteVideo', {id: e.id}, r => {
          console.log('删除视频', r)
          if (r.code == 1) {
            that.$toast(r.info)
            that.$router.replace({
              path: '/refresh',
              query: {
                pid: that.pid,
                bid: that.bid,
                t: Date.now()
              }
            });
          }
        })
      },

      onSave() {
        this.showDelete = false;
      },

      showPopup() {
        this.show = true;
        console.log('show', this.show);
      },

      getVideo(ev, typer) {
        let that = this;
        that.showPopup();
        //获取上传文件标签
        let filesId = document.getElementById('pop_video');
        //获取音频标签
        let videoId = this.$refs.videoId;
        //把当前files[0]传给getFileURL方法， getFileURL方法对其做一处理
        console.log('视频资源', filesId.files[0])
        that.videoFiles = filesId.files[0];

        let url = this.getFileURL(filesId.files[0])
        console.log('视频地址', url)
        console.log(videoId)
        if (url) {
          //给video标签设置src
          videoId.src = url
        }
        console.log(url)
      },

      onUpVideo() {
        console.log('点击上传')
        let that = this;
        let formData = new FormData();
        formData.append("video", that.videoFiles);
        formData.append('bid', that.bid);
        formData.append('sid', that.sid);
        formData.append('create_time', that.valueTime);
        that.$http.post('/api/MobileAadminApi/addVideo/', formData, r => {
          console.log('上传视频r:', r)
          if (r.code == 1) {
            that.$toast(r.info);
            that.show = false;
            that.$router.replace({
              path: '/refresh',
              query: {
                pid: that.pid,
                bid: that.bid,
                t: Date.now()
              }
            });
          }
        })
      },

      getFileURL(file) {
        let getUrl = null
        if (window.createObjectURL != undefined) {
          //basic
          getUrl = window.createObjectURL(file)
        } else if (window.URL != undefined) {//window.URL 标准定义
          //mozilla(firefox)
          //获取一个http格式的url路径，这个时候就可以设置<img>中的显示
          getUrl = window.URL.createObjectURL(file)
        } else if (window.webkitURL != undefined) {//window.webkitURL是webkit的内核
          //webkit or chrome
          getUrl = window.webkitURL.createObjectURL(file)
        }
        return getUrl

        //video 标签的 duration属性，获取当前视频的长度
        // let duration = videoId.duration
        // if (Math.floor(duration) > 60) {
        // that.layer.msg('视频不能大于60秒')
        // }
      },

      onTimeConfirm(time) {
        console.log(time)
        let year = time.getFullYear()
        let month = time.getMonth() + 1
        let day = time.getDate()
        let hour = time.getHours();
        let minute = time.getMinutes();
        //let second = time.getSeconds();
        this.valueTime = `${year}-${month}-${day} ${hour}:${minute}:00`;
        this.showTimePicker = false;
      },

    }
  }
</script>

<style scoped>
  .switch_name {
    padding: 10px;
    background: #ffffff;
  }

  .switch_name >>> .van-cell {
    padding: 10px;
    background: #f3f3f3;
    border-radius: 5px;
  }

  .video_main {
    display: flex;
    flex-flow: row wrap;
    margin: 0 10px 1rem;
    justify-content: space-between;
  }
  .video_wrapper >>> .van-list{
     padding-bottom: 1.5rem;
  }


  .video_item {
    position: relative;
    width: 48%;
    height: 2.5rem;
    margin-top: 15px;
    box-sizing: border-box;
    border-radius: 8px;
    overflow: hidden;
  }

  .video_item >>> img {
    width: 100%;
    display: block;
    height: 2.5rem;
  }

  .video_item >>> .icon-bofang- {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
    width: 36px;
    height: 36px;
  }

  .video_item >>> .van-icon-clear {
    position: absolute;
    right: -10px;
    top: -10px;
    background: #fff;
    border-radius: 50%;
  }

  .inputVideo {
    height: 1rem;
    line-height: 1rem;
    background: var(--color-tint);
    color: #fff;
    font-size: .36rem;
    border-radius: 5px;
    text-align: center;
  }

  .upload_box_title {
    height: 44px;
    line-height: 44px;
    font-size: 16px;
    text-align: center;
    background: var(--color-tint);
    color: #fff;
    font-weight: normal;
  }

  .upload_box >>> .van-popup__close-icon {
    top: 11px;
    color: #fff;
  }
  .video_date{
    position: absolute;
    bottom: 0;
    left:0;
    right:0;
    width:100%;
    text-align: center;
    height:.5rem;
    line-height: .5rem;
    font-size: .28rem;
    background: rgba(255,255,255,0.8);
  }
</style>
